# echoserver.py
#
# A concurrent echo server using coroutines
#
# Original code by David Beazley (http://www.dabeaz.com).


from socket import *

from wheels.pi.aio import Exit
from wheels.pi.aio.System import System

from wheels.pi.net.ServiceHandler import ServiceHandler
from wheels.pi.net.Acceptor import Acceptor
from wheels.pi.net.TcpAcceptor import TcpAcceptor


class EchoHandler(ServiceHandler):

    def __init__(self):
        ServiceHandler.__init__(self)


    def open(self):
        print "Connection from", self._peer_stream.remote_address()
        while True:
            data = yield self._read()
            if not data:
                break
            print "> ", data.strip()
            if data.strip() == "exit":
                yield Exit()
            yield self._write(data)
        print "Closing connection"
        self.close()


class EchoAcceptor(Acceptor):

    def __init__(self):
        tcp = TcpAcceptor()
        tcp.reuse_address(True)
        Acceptor.__init__(self, tcp, EchoHandler);


def server(port):
    print "Server starting"
    acc = EchoAcceptor()
    acc.open(("", port))
    while True:
        yield acc.accept()


sys = System()
sys.new_task(server(45000))
sys.main()
